package xin.printk.android;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import xin.printk.android.data.entity.HomeItem;
import xin.printk.android.data.entity.NoteItem;
import xin.printk.android.data.event.LoginEvent;
import xin.printk.android.module.favorites.FavoritesActivity;
import xin.printk.android.module.login.LoginActivity;
import xin.printk.android.module.note.NoteActivity;
import xin.printk.android.module.plan.PlanActivity;
import xin.printk.android.module.setting.SettingActivity;
import xin.printk.android.module.theme.ThemeActivity;
import xin.printk.android.module.user.UserActivity;
import xin.printk.android.utils.AppConstants;
import xin.printk.android.utils.LogUtils;
import xin.printk.android.utils.Mock;
import xin.printk.android.utils.PrefUtils;
import xin.printk.android.utils.RequestCallback;
import xin.printk.android.view.adapter.CycleViewPagerAdapter;
import xin.printk.android.view.adapter.HomeRecyclerAdapter;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private ConstraintLayout mRightLayout;
    private NavigationView mLeftLayout;
    private DrawerLayout mDrawerLayout;
    private ConstraintLayout mToolbarLayout;
    private ConstraintLayout mBannerLayout;
    private List<NoteItem> mNoteItems;

    private WindowManager mWindowManager;
    private Display mDefaultDisplay;
    private Point mDisplayPoint;

    private Button mLoginButton;
    private TextView mLoginTipsText;
    private ImageView mAvatarImage;
    private TextView mUsernameText;

    private int mBannerHeight = 0;
    private int mScrollPosition = 0;
    private int mToolbarAlpha = 1;
    private int mCurrentIndex = 0;

    private List<HomeItem> mHomeItems;
    private HomeRecyclerAdapter mHomeRecyclerAdapter;

    private ViewPager mBannerPager;
    private static final int TIME_DELAYED = 5000;
    private static final int TIME_DELAYED_MSG = 0x100;
    private TimerHandler mBannerHandler;
    private Timer mTimer;
    private TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            mBannerHandler.sendEmptyMessage(TIME_DELAYED_MSG);
        }
    };

    private static class TimerHandler extends Handler {

        WeakReference<Activity> weakReference;
        RequestCallback callback;

        TimerHandler(Activity activity, RequestCallback callback) {
            weakReference = new WeakReference<>(activity);
            this.callback = callback;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final Activity activity = weakReference.get();
            if (activity != null) {
                if (callback != null) {
                    callback.onSuccess(msg);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        mDisplayPoint = new Point();

        mDrawerLayout = findViewById(R.id.drawer_main);
        mRightLayout = findViewById(R.id.layout_main);
        mLeftLayout = findViewById(R.id.nav_menu_view);
        mToolbarLayout = findViewById(R.id.toolbar_layout);
        mBannerHeight = (int) getResources().getDimension(R.dimen.banner_height);
//        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
//                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//        mDrawerLayout.addDrawerListener(toggle);
//        toggle.syncState();

        mLeftLayout.setNavigationItemSelectedListener(this);
        mDrawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                LogUtils.d("slideOffset : " + slideOffset);
                if (mWindowManager != null) {
                    mDefaultDisplay = mWindowManager.getDefaultDisplay();
                    if (mDefaultDisplay != null) {
                        mDefaultDisplay.getSize(mDisplayPoint);
                        LogUtils.d("mLeftLayout.getLeft() = " + mLeftLayout.getLeft() + " mLeftLayout.getRight() = " + mLeftLayout.getRight());
                        LogUtils.d("mRightLayout.getLeft() = " + mRightLayout.getLeft() + " mRightLayout.getRight() = " + mRightLayout.getRight());
                        LogUtils.d("x = " + mDisplayPoint.x + " y = " + mDisplayPoint.y);
                        mRightLayout.layout(mLeftLayout.getRight(), 0,
                                mLeftLayout.getRight() + mDisplayPoint.x, mDisplayPoint.y);
                    }
                }
            }

        });

        RecyclerView mHomeRecyclerView = findViewById(R.id.rv_home_list);
        mHomeItems = Mock.mockHomeItemData(this);
        mHomeRecyclerAdapter = new HomeRecyclerAdapter(this, mHomeItems);
        mHomeRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mHomeRecyclerView.setAdapter(mHomeRecyclerAdapter);
        mHomeRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LogUtils.d("dx = " + dx + " dy = " + dy);
                mScrollPosition += dy;
                LogUtils.d("mScrollPosition is " + mScrollPosition + " mBannerHeight is " + mBannerHeight);
                if (mScrollPosition <= (mBannerHeight * 2)) {
                    mToolbarAlpha = mScrollPosition * 255 / mBannerHeight;
                    mToolbarAlpha = mToolbarAlpha > 255 ? 255 : mToolbarAlpha;
                    mToolbarLayout.getBackground().mutate().setAlpha(mToolbarAlpha);
                    LogUtils.d("toolbar set alpha is " + mToolbarAlpha);
                }
            }
        });

        View view = LayoutInflater.from(this).inflate(R.layout.layout_banner_view, mHomeRecyclerView, false);
        mBannerLayout = view.findViewById(R.id.banner_layout);
        mBannerPager = view.findViewById(R.id.vp_banner_pager);
        mNoteItems = Mock.mockMoreNoteItemData(this);
        final List<View> mViewList = mockView(mBannerPager, mNoteItems);
        PagerAdapter mPagerAdapter = new CycleViewPagerAdapter<>(mViewList);
        mBannerPager.setOffscreenPageLimit(mViewList.size());
        mBannerPager.setPageMargin(48);
        mBannerPager.setAdapter(mPagerAdapter);
        mBannerPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                LogUtils.d("current item title is " + mNoteItems.get(position).getTitle());
                if (position <= 1) {
                    mCurrentIndex = mViewList.size() - 2;
                } else if (position >= mViewList.size() - 2) {
                    mCurrentIndex = 2;
                } else {
                    mCurrentIndex = position;
                }
                LogUtils.d("view pager position is " + position + " and mCurrentIndex is " + mCurrentIndex);
                mBannerLayout.setBackgroundColor(mNoteItems.get(mCurrentIndex).getColor());
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    LogUtils.d("setCurrentItem is " + mCurrentIndex);
                    mBannerPager.setCurrentItem(mCurrentIndex, false);
                }
            }
        });
        mBannerPager.setCurrentItem(2);
        mBannerHandler = new TimerHandler(this, new RequestCallback() {
            @Override
            public <T> void onSuccess(T t) {
                Message msg = (Message) t;
                if (msg != null) {
                    if (msg.what == TIME_DELAYED_MSG) {
                        mBannerPager.setCurrentItem(++mCurrentIndex);
                    }
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
        mHomeRecyclerAdapter.setHeaderView(view);

        View headerView = mLeftLayout.getHeaderView(0);
        mLoginButton = headerView.findViewById(R.id.bt_goto_login);
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        });
        mLoginTipsText = headerView.findViewById(R.id.tv_login_tip);
        mAvatarImage = headerView.findViewById(R.id.img_avatar);
        mUsernameText = headerView.findViewById(R.id.tv_username);
        mAvatarImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, UserActivity.class));
            }
        });

        mTimer = new Timer();

        LogUtils.d("MainActivity register EventBus");
        EventBus.getDefault().register(this);
    }

    //    private int mBannerImageResId[] = {R.mipmap.banner_image1, R.mipmap.banner_image2, R.mipmap.banner_image3};
    private int mBannerImageResId[] = {R.mipmap.cover_android, R.mipmap.cover_java, R.mipmap.cover_kotlin,
            R.mipmap.cover_cplusplus, R.mipmap.cover_linux, R.mipmap.cover_data_structure,
            R.mipmap.cover_network, R.mipmap.cover_database};

    private List<ImageView> getBannerImage() {
        List<ImageView> mImageList = new ArrayList<>();
        for (int id : mBannerImageResId) {
            ViewGroup.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            ImageView image = new ImageView(this);
            image.setLayoutParams(lp);
            image.setScaleType(ImageView.ScaleType.CENTER_CROP);
            image.setImageResource(id);
            mImageList.add(image);
        }
        return mImageList;
    }

    private List<View> mockView(ViewGroup parent, List<NoteItem> data) {
        List<View> views = new ArrayList<>();
        LayoutInflater inflater = LayoutInflater.from(this);
        for (int i = 0; i < data.size(); i++) {
            View view = inflater.inflate(R.layout.item_banner, parent, false);
            CardView layout = view.findViewById(R.id.item_layout);
            TextView title = view.findViewById(R.id.tv_banner_title);
            TextView description = view.findViewById(R.id.tv_banner_description);
            layout.setBackgroundColor(data.get(i).getColor());
            title.setText(data.get(i).getTitle());
            description.setText(data.get(i).getDescription());
            views.add(view);
        }
        return views;
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_favourite:
                startActivity(new Intent(MainActivity.this, FavoritesActivity.class));
                break;
            case R.id.nav_plan:
                startActivity(new Intent(MainActivity.this, PlanActivity.class));
                break;
            case R.id.nav_note:
                startActivity(new Intent(MainActivity.this, NoteActivity.class));
                break;
            case R.id.nav_history:
                break;
            case R.id.nav_switch_theme:
                startActivity(new Intent(MainActivity.this, ThemeActivity.class));
                break;
            case R.id.nav_setting:
                startActivity(new Intent(MainActivity.this, SettingActivity.class));
                break;
            default:
                break;
        }
        LogUtils.d("mLeftLayout.getLeft() = " + mLeftLayout.getLeft() + " mLeftLayout.getRight() = " + mLeftLayout.getRight());
        LogUtils.d("mRightLayout.getLeft() = " + mRightLayout.getLeft() + " mRightLayout.getRight() = " + mRightLayout.getRight());
        // mDrawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        int color = PrefUtils.getInt(AppConstants.THEME_COLOR, getResources().getColor(R.color.blue_light));
        mBannerLayout.setBackgroundColor(mNoteItems.get(mCurrentIndex).getColor());
        mToolbarLayout.setBackgroundColor(color);
        mLeftLayout.setItemIconTintList(ColorStateList.valueOf(color));
        mToolbarLayout.getBackground().mutate().setAlpha(mToolbarAlpha);
        for (int i = 0; i < mHomeItems.size(); i++) {
            mHomeItems.get(i).setColor(color);
        }
        mHomeRecyclerAdapter.notifyDataSetChanged();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                mBannerHandler.sendEmptyMessage(TIME_DELAYED_MSG);
            }
        };
        mTimer.schedule(mTimerTask, TIME_DELAYED, TIME_DELAYED);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mTimerTask != null) {
            mTimerTask.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.purge();
            mTimer.cancel();
            mTimer = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            LogUtils.d("MainActivity unregister EventBus");
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event.isOnline()) {
            mLoginButton.setVisibility(View.GONE);
            mLoginTipsText.setVisibility(View.GONE);
            mAvatarImage.setVisibility(View.VISIBLE);
            mUsernameText.setVisibility(View.VISIBLE);
        } else {
            mLoginButton.setVisibility(View.VISIBLE);
            mLoginTipsText.setVisibility(View.VISIBLE);
            mAvatarImage.setVisibility(View.GONE);
            mUsernameText.setVisibility(View.GONE);
        }
    }
}
